package io.gitee.thant.utils;

import java.util.HashSet;
import java.util.Set;

public class DigitUtil {
	private static final String defaultDigitdef = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz$@";

	private String digitdef = null;
	
	public DigitUtil(String def) {
		if (def != null) {
			Set<Character> s = new HashSet<Character>();
			for (int i=def.length()-1;i>=0;--i) {
				s.add(def.charAt(i));
			}
			if (s.size() == def.length() && def.length()>=2) { //def不能有重复的字符
				digitdef = def;
			}
		}
	}

	public DigitUtil(int base) {
		if (0>base || base>64) return;
		digitdef = defaultDigitdef.substring(0, base);
	}
	
	public String toString(int d) {
		return toString(d, 0, ' ');
	}
	
	public String toString(int d, int len, char space) {
		if (StringUtil.isEmpty(digitdef)) return null;
		
		char flag = 0;
		if (d<0) {
			d = -d;
			flag = '-';
		}
		
		StringBuilder sb = new StringBuilder();
		int cur = d, tmp, rem=0;
		int base = digitdef.length();
		do {
			tmp = cur / base;
			rem = cur - tmp*base;
			cur = tmp;
			sb.append(digitdef.charAt(rem));
		} while(cur>=base);
		if (cur>0) {
			sb.append(digitdef.charAt(cur));
		}
		
		int pos = 0;
		if (flag!=0) {
			sb.append(flag);
			pos = 1;
		}

		sb = sb.reverse();
		int spacelen = len-sb.length(); 
		if (spacelen>0) {
			char[] spaceA = new char[spacelen];
			for (int i=0;i<spacelen;++i) {
				spaceA[i]=space;
			}
			sb.insert(pos, spaceA);
		}
		return sb.toString();
	}
	
	public int toValue(String s) {
		if (StringUtil.isEmpty(digitdef)) return Integer.MAX_VALUE;
		
		int b=0,flag = 1;
		if ('-' == s.charAt(0)) {
			flag = -1;
			b=1;
		} else if ('+' == s.charAt(0)) {
			b=1;
		}
		
		int sum = 0;
		int base = digitdef.length();
		for (int sb=1,i=s.length()-1;i>=b;i--) {
			char c = s.charAt(i);
			int dc = digitdef.indexOf(c);
			if (dc<0) return Integer.MAX_VALUE;
			sum += dc*sb;
			sb *= base;
		}
		return flag*sum;
	}
}
